package com.billjc.activity.service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.activiti.engine.delegate.BpmnError;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.billjc.activity.dao.PlatsysDao;
import com.billjc.activity.entities.ECSAppInfo;
import com.billjc.activity.entities.ECSBOErrorList;
import com.billjc.activity.entities.ECSClntinfoChg;
import com.billjc.activity.entities.ECSEFormReturn;
import com.billjc.activity.entities.Ecs;
import com.billjc.activity.model.EformRequestXml;
import com.billjc.activity.model.FormData;
import com.billjc.activity.model.FormDataRequest;
import com.billjc.activity.model.FormDataReturn;
import com.billjc.activity.prop.EcsGlobalVariable;
import com.billjc.activity.util.PropertiesUtil;
import com.billjc.activity.util.TransXmlUtil;

@Service
public class CreateEformService {
	@Autowired
	private PlatsysDao platsysDao;
	@Autowired
	private EcsGlobalVariable global;
	/**
	 * call eform webService服务
	 * @param ecs
	 */
	public void executeService(Ecs ecs) {
		String requestXml = initEform(ecs);
		ecs.getEFormInfo().setEFormRequestXml(requestXml);
		//ecs.getEFormInfo().toBuilder().eFormRequestXml(requestXml);
		String responseXml = null;
		EformRequestXml response = null;
    	try {
    		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        	Client client = dcf.createClient(global.getEFormWSDL());
			Object[] objects = client.invoke("FormSubmit", requestXml);
			for(Object responseObject : objects) {
				responseXml = responseObject.toString();
			}
			ecs.getEFormInfo().setEFormResponseXml(responseXml);
			response = analysisResponse(responseXml);
		} catch (Exception e) {
			throw new BpmnError("createError");
		}
    	if(Objects.nonNull(response)) {
    		ecs.getEFormInfo().setEFormReturn(ECSEFormReturn.builder().returnMess(response.getFormData().getFormDataReturn().getReturnMess())
    				.formDataID(response.getFormData().getFormDataReturn().getFormDataID()).build());
    	}
	}
    /**
     * 组装eform报文
     * @param ecs
     */
	private String initEform(Ecs ecs) {
		String appType = "";
		String appTypeName = "";
		String errorMsg = "";
		ECSAppInfo appInfo = ecs.getAppInfo();
		ECSClntinfoChg clntInfo = ecs.getClntInfo();
        String appNum = appInfo.getAppNum();
        List<Map<String, Object>> resutlList = platsysDao.selectAppType(appNum);
        if(CollectionUtils.isNotEmpty(resutlList)) {
        	Map<String, Object> targetMap = resutlList.get(0);
        	String appTypeResult = (String) targetMap.get("AppType");
        	if(StringUtils.equals(appTypeResult, global.getAppTypeWeC())) {
        		appType = "微信";
        	}else if (StringUtils.equals(appTypeResult, global.getAppTypeWeM())) {
        		appType = "移动端";
			}else {
				appType = "外网";
			}
        }else {
        	appType = "缺省";
        }
		try {
			appTypeName = PropertiesUtil.read("config/appType.properties", appInfo.getAppType());
		} catch (Exception e) {
			e.printStackTrace();
		}
        if(StringUtils.isEmpty(appTypeName)) {
        	appTypeName = "通讯地址变更";
        }
        
        if(Objects.nonNull(ecs.getLAResult().getBOError())) {
        	List<ECSBOErrorList> errorList = ecs.getLAResult().getBOError().getErrorList();
        	for(ECSBOErrorList error : errorList) {
        		errorMsg+=error.getDesc();
        	}
        }
        String address = clntInfo.getCltAddr01()+clntInfo.getCltAddr02()+clntInfo.getCltAddr03()+clntInfo.getCltAddr04()+clntInfo.getCltAddr05();
        //构建报文对象
        FormDataRequest formDataRequest = FormDataRequest.builder().PolicyNo(appInfo.getFullChdrnum())
        		.CustomerNo(appInfo.getClntNum()).SubmiteDate(appInfo.getAppDate())
        		.CustomerName(appInfo.getSurName()).ApplyMethod(appType).ApplyNotice(appTypeName)
        		.Address(address).Zip(clntInfo.getCltPCode()).MobilePhone(clntInfo.getRmblPhone())
        		.TelPhone(clntInfo.getCltPhone01()).OfficePhone(clntInfo.getCltPhone02())
        		.AcceptSMS(StringUtils.equals("Y", clntInfo.getSmsSel())?"是":"否")
        		.Email(clntInfo.getRinternet()).Memo(errorMsg).build();
        FormData formData = FormData.builder().TransRefGUID(ecs.getBPMInfo().getBPDNum()).formDataRequest(formDataRequest).formDataReturn(FormDataReturn.builder().FormDataID("").ReturnFlag("").ReturnMess("").build()).build();
        EformRequestXml requestXml = EformRequestXml.builder().formData(formData).FormType("GenWebOptServImg").build();
        TransXmlUtil marshaller = new TransXmlUtil();
        String eformRequest = marshaller.marshal(requestXml);
        return eformRequest;
	}
	/**
	 * 解析返回报文
	 * @param responseXml
	 * @return
	 */
	private EformRequestXml analysisResponse(String responseXml) {
		TransXmlUtil marshaller = new TransXmlUtil();
		EformRequestXml response = EformRequestXml.builder().build();
		response = marshaller.unmarshal(responseXml, response);
		return response;
	}
}
